package com.xunyun.kotlinwc.main.fragment

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.xunyun.kotlinwc.R
import com.xunyun.kotlinwc.base.BaseFragment
import com.xunyun.kotlinwc.databinding.FragmentHomeBinding
import com.xunyun.kotlinwc.main.adapter.ArticlePageAdapter
import com.xunyun.kotlinwc.main.adapter.ImageAdapter
import com.xunyun.kotlinwc.main.viewmodel.HomeViewModel
import com.xunyun.kotlinwc.utils.ToastUtils
import com.xunyun.kotlinwc.utils.paging.DiffCallback


class HomeFragment : BaseFragment<FragmentHomeBinding, HomeViewModel>() {

    private val adapter by lazy { ArticlePageAdapter(DiffCallback()) }

    override fun getLayoutId(): Int {
        return R.layout.fragment_home
    }

    override fun getViewModel(): HomeViewModel {
        return HomeViewModel()

    }

    override fun bindViewModel() {
        //绑定LifecycleOwner 处理 rxjava内存泄露
        mViewModel.bindLifecycleOwner(this)

    }

    override fun initView(view: View, savedInstanceState: Bundle?) {
        mBinding.recyclerView.layoutManager = LinearLayoutManager(mContext)
        /* val diff: DiffCallback<Article> = DiffCallback();
          val adapter = ArticlePageAdapter(diff) */
        mBinding.recyclerView.adapter = adapter;
        mViewModel.getBannerData()

        mViewModel.mListLiveData.observe(this, Observer {
            adapter.submitList(it)
            if (mBinding.refreshLayout.isRefreshing) {
                mBinding.refreshLayout.isRefreshing = false;
            }
        })

        mViewModel.bannerListLiveData.observe(this, Observer {
            mBinding.banner.setAdapter(ImageAdapter(mContext, it))
        })

        mViewModel.infoMsg.observe(this, Observer {
            ToastUtils.showInfo(it)
        })


        mBinding.refreshLayout.setOnRefreshListener {
            mViewModel.refresh()
        }

    }

    override fun onDestroyView() {
        super.onDestroyView()
        Log.e("HomeFragment","onDestroyView")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.e("HomeFragment","onDestroy")
    }


}